package com.taotao.order.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.taotao.common.pojo.TaotaoResult;
import com.taotao.pojo.TbUser;
import com.taotao.sso.service.UserService;
import com.taotao.utils.CookieUtils;
import com.taotao.utils.JsonUtils;

public class LoginInterceptor implements HandlerInterceptor {
	
	@Autowired
	private UserService userService;
	
	@Value("${TT_TOKEN}")
	private String TT_TOKEN;

	@Override
	public void afterCompletion(HttpServletRequest request,
			HttpServletResponse response, Object handler, Exception arg3)
			throws Exception {
		
	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response,
			Object handler, ModelAndView arg3) throws Exception {
		
		
	}

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
			Object handler) throws Exception {
		String token = CookieUtils.getCookieValue(request, TT_TOKEN);
		if(StringUtils.isBlank(token)){
			
			String requestURL = request.getRequestURI().toString();
			response.sendRedirect("http://localhost:8088/page/login?url="+requestURL);
			
			return false;
		}
		TaotaoResult taotaoResult = userService.getUserByToken(token);
		if(taotaoResult.getStatus()!=200){
			String requestURL = request.getRequestURI().toString();
			response.sendRedirect("http://localhost:8088/page/login?url="+requestURL);
			return false;
		}
		TbUser user = (TbUser) taotaoResult.getData();
		
		request.setAttribute("user", user);
		
		
		
		return true;
	}

}
